using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using UniversalAdmin.Api.Models;
using UniversalAdmin.Api.Models.Auth;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Api.Filters;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Api.Controllers
{
    /// <summary>
    /// 认证控制器
    /// </summary>
    [ApiController]
    [Route("api/auth")]
    public class AuthController : ControllerBase
    {
        private readonly IAuthService _authService;
        private readonly IUnitOfWork _unitOfWork;

        public AuthController(IAuthService authService, IUnitOfWork unitOfWork)
        {
            _authService = authService;
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        [HttpPost("register")]
        [AllowAnonymous]
        public async Task<IActionResult> Register([FromBody] RegisterRequest request)
        {
            if (!ModelState.IsValid)
                return BadRequest(ApiResponse.Error(400, "请求参数错误"));

            var result = await _authService.RegisterAsync(request.Username, request.Email, request.Password);

            if (result.Success)
            {
                var responseData = new LoginResponseData
                {
                    Token = result.AccessToken!,
                    RefreshToken = result.RefreshToken!,
                    ExpiresIn = result.ExpiresIn,
                    User = new Models.Auth.UserInfo
                    {
                        Id = result.User!.Id,
                        Username = result.User.Username,
                        Email = result.User.Email,
                        Avatar = null,
                        Roles = result.User.Roles
                    }
                };

                return Ok(ApiResponse<LoginResponseData>.Success(responseData, "注册成功"));
            }

            return BadRequest(ApiResponse.Error(400, result.ErrorMessage ?? "注册失败"));
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        [HttpPost("login")]
        [AllowAnonymous]
        [SkipAuditLog]  //标记这条 Action 不记录
        public async Task<IActionResult> Login([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
                return BadRequest(ApiResponse.Error(400, "请求参数错误"));

            var result = await _authService.LoginAsync(request.Username, request.Password);

            if (result.Success)
            {
                var responseData = new LoginResponseData
                {
                    Token = result.AccessToken!,
                    RefreshToken = result.RefreshToken!,
                    ExpiresIn = result.ExpiresIn,
                    User = new Models.Auth.UserInfo
                    {
                        Id = result.User!.Id,
                        Username = result.User.Username,
                        Email = result.User.Email,
                        Avatar = null, // TODO: 从数据库获取头像
                        Roles = result.User.Roles
                    }
                };

                return Ok(ApiResponse<LoginResponseData>.Success(responseData, "登录成功"));
            }

            return BadRequest(ApiResponse.Error(400, result.ErrorMessage ?? "登录失败"));
        }

        /// <summary>
        /// 用户登出
        /// </summary>
        [HttpPost("logout")]
        [Authorize]
        public IActionResult Logout()
        {
            // JWT是无状态的，登出主要是客户端删除Token
            return Ok(ApiResponse.Success("登出成功"));
        }

        /// <summary>
        /// 刷新Token
        /// </summary>
        [HttpPost("refresh")]
        [AllowAnonymous]
        public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequest request)
        {
            if (!ModelState.IsValid)
                return BadRequest(ApiResponse.Error(400, "请求参数错误"));

            var result = await _authService.RefreshTokenAsync(request.RefreshToken);

            if (result.Success)
            {
                var responseData = new
                {
                    Token = result.AccessToken,
                    RefreshToken = result.RefreshToken,
                    ExpiresIn = result.ExpiresIn
                };

                return Ok(ApiResponse<object>.Success(responseData, "刷新成功"));
            }

            return BadRequest(ApiResponse.Error(400, result.ErrorMessage ?? "刷新失败"));
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        [HttpGet("profile")]
        [Authorize]
        public async Task<IActionResult> GetProfile()
        {
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (userIdClaim == null || !int.TryParse(userIdClaim, out var userId))
                return Unauthorized(ApiResponse.Error(401, "未授权"));

            // 从数据库获取完整的用户信息
            var user = await _unitOfWork.UserRepository.GetByIdAsync(userId);
            if (user == null)
                return NotFound(ApiResponse.Error(404, "用户不存在"));

            // 获取用户角色
            var roles = await _authService.GetUserRolesAsync(userId);

            var profile = new UserProfile
            {
                Id = userId,
                Username = user.Username,
                Email = user.Email ?? "",
                Phone = user.Phone ?? "",
                Avatar = user.Avatar ?? "",
                IsActive = user.IsActive,
                CreatedAt = user.CreatedAt,
                Roles = roles.Select(r => new RoleInfo { Name = r }),
                Permissions = new[] { "user.view" } // TODO: 实现权限系统
            };

            return Ok(ApiResponse<UserProfile>.Success(profile, "获取成功"));
        }
    }
}
